from pydantic import BaseModel

# coding: utf-8
from sqlalchemy import BigInteger, CHAR, Column, DateTime, Integer, String, event, Table, ForeignKey
from sqlalchemy.dialects.mysql import TINYINT
from datetime import datetime
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from models.base import Base
metadata = Base.metadata


class SysRole(Base):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    __tablename__ = 'sys_roles'

    id = Column(Integer, primary_key=True, comment='角色ID')
    role_name = Column(String(30, 'utf8mb4_unicode_ci'), nullable=False, comment='角色名称')
    role_key = Column(String(100, 'utf8mb4_unicode_ci'), nullable=False, comment='角色权限字符串')
    role_sort = Column(Integer, nullable=False, comment='显示顺序')
    data_scope = Column(CHAR(1, 'utf8mb4_unicode_ci'), comment='数据范围（1：全部数据权限 2：自定数据权限 3：本部门数据权限 4：本部门及以下数据权限）')
    menu_check_strictly = Column(TINYINT(1), comment='菜单树选择项是否关联显示')
    dept_check_strictly = Column(TINYINT(1), comment='部门树选择项是否关联显示')
    status = Column(CHAR(1, 'utf8mb4_unicode_ci'), nullable=False, comment='角色状态（0正常 1停用）')
    del_flag = Column(CHAR(1, 'utf8mb4_unicode_ci'), comment='删除标志（0代表存在 2代表删除）')
    create_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='创建者')
    update_by = Column(String(64, 'utf8mb4_unicode_ci'), comment='更新者')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    deleted_at = Column(DateTime, comment='删除时间')
    remark = Column(String(500, 'utf8mb4_unicode_ci'), comment='备注')
    role_menus = relationship('SysRoleMenu', back_populates='role')


@event.listens_for(SysRole, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(SysRole, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")


class SysRoleSchema(BaseModel):
    id: int
    role_name: str
    role_key: str
    role_sort: int
    data_scope: str
    menu_check_strictly: int
    dept_check_strictly: int
    status: str
    del_flag: str
    create_by: str
    update_by: str
    remark: str

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True
